package com.xidian.zhiancloud.service.chemicalsManagement.chemicalManager.dangerousPart;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.DangerCategoryMapper;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.DangerCategory;
import com.xidian.zhiancloud.qo.chemicalsManagement.DangerCategoryQO;
import com.xidian.zhiancloud.vo.chemicalsManagement.DangerCategoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: Egoist
 * @Date: 2020/11/10 17:00
 */

@Service
public class DangerCategoryService extends ServiceImpl<DangerCategoryMapper, DangerCategory> implements IService<DangerCategory> {

    @Autowired
    private DangerCategoryMapper dangerCategoryMapper;

    public IPage<DangerCategoryVO> getListByQueryObject(DangerCategoryQO dangerCategoryQO) {
        Page<DangerCategoryVO> page = new Page<>(dangerCategoryQO.getCurrent(), dangerCategoryQO.getSize());
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderItem);
        return dangerCategoryMapper.getListByQO(page, dangerCategoryQO);

    }

    public ResultDTO<Boolean> saveInfo(DangerCategory dangerCategory) {
        QueryWrapper<DangerCategory> query = new QueryWrapper<DangerCategory>();
        query.eq("company_id", dangerCategory.getCompanyId());
        List<DangerCategory> list = list(query);
        for (DangerCategory category : list) {
            if (category.getName().equals(dangerCategory.getName())) {
                return ResultDTO.errorOf(-1, category.getName() + " 已存在!");
            }
        }
        return ResultDTO.successOf(save(dangerCategory), GeneralResponseEnums.SUCCESS);
    }

    public ResultDTO<Boolean> updateCheckNameById(DangerCategory dangerCategory, Long companyId) {
        String name = dangerCategory.getName();
        QueryWrapper<DangerCategory> query = new QueryWrapper<DangerCategory>();
        query.eq("company_id", companyId);
        List<DangerCategory> list = list(query);
        for (DangerCategory category : list) {
            if (name.equals(category.getName()) && !dangerCategory.getId().equals(category.getId())) {
                return ResultDTO.errorOf(-1, category.getName() + " 已存在!");
            }
        }
        return ResultDTO.successOf(updateById(dangerCategory), GeneralResponseEnums.SUCCESS);
    }
}

